const net = require('net')
const clientList = {}

chatServer = net.createServer()

chatServer.on('connection', (client) => {
  console.log(client._handle.fd, new Date())
  client.write('Hi!\n')
  clientList[client._handle.fd] = client 
  
  client.on('data', (data) => {
    console.log('data', data.toString())
    
    if(data.toString() === 'QUIT') {
      delete clientList[client._handle.fd]
      client.end()  
    }

    broadcast(data, client)
  })

  client.on('end', (data) => {
    console.log('client quit from server')
  })

})

chatServer.on('close', () => {
  console.log('关闭服务器。。。。。')
})

chatServer.on('error', (error) => {
  console.log(error)
})

function broadcast(msg, client) {
  for(let clientFd in clientList) {
    if(String(client._handle.fd) !== String(clientFd)) {
      clientList[clientFd].write(msg)
    } else {
      clientList[clientFd].write("消息已发出:\n" + msg)
    }
  }
}

chatServer.listen(9000)

console.log(`CHAT SERVER START ON ${new Date()}`)
